package com.qf.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.qf.entity.Order;
import com.qf.feign.api.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RequestMapping("/pay")
@Controller
public class PayController {

    String serverUrl = "https://openapi.alipaydev.com/gateway.do";
    String appid = "2016101000656227";
    String prikey = "MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQC/mbBjrv+L/jdsZgtNkSZdQ+ExDbsDY0WeAIyBVQarzrrxf7wsW+JaE5uyWjxIXCo8fl7xip0kn7Tifz2z6YJ5qupt/ZCTlJK2sFW4eECSnt16p4ujaSnPxGklAh+IP2ipUYURosXTXB8RSEQr535/2eGc57JKXFZQmREo6xNA8Yx6FSwadskXWCXMlGJz6PYqOR6m7TG1mKn5AeEmdmLUQ7iuwf/IwOGXkEpW+eHbUb6WM6aX8R+7VYwCGhBscg+M9FJjfrXtYkSWuF8eezQrY61EAQcTpM+BWcR7ZR5iyz4Jj7bd5b3dYx0paZQ54+Pgd0Gj/W8IAYquKhPRTuL5AgMBAAECggEAfz9N41ZEx6/FFUvMM+6zYPuE4nQxALX8dUv+BKL4dEAu7dacnYVElfgxzkiZgqEbN+PhoF8jsEAU/Nvumb76dV1qpjPhwfHJYmVH+OR8ViQGCcCeP5/HMgJKplZ7pJwgIVtPmf/VjGLBC1RIWjQ7UiPc77z9Lt+WP574w4kj11usPnzBoIM5owTyv/PqkpWLG4ZwUZK3cgSuDm4v8R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htynNGDxdFVYrwT8jP2gu3VsRu7CSfdsAfuDTrwmeuKeaQCBQ19gSAslwTzfip8ebIsiA6jnhRrpNbd+c3FxBxHR6tB6pG2tvBPB6EtQAStRTjPWkiTF1laTbcynuKsiW8X4dgX92PxPfW/Fx8bHgDgxrEBhrURUtZHuQh6VBdUyLHAnpVKU+zQ06p+h4H4O/Ch+fv0KAzAHe9Z1XVot2hswa+UJM1H2am5y2DU5K1gw3s8anGoOMnc4tFsXW4yDEZQrspxbhtLiU7tWc4fvd4GEQ7Ye7OoPIWtUZq1iyra8TMtT2KIhyYRqj+1K21HyMsJkmf0cvwIDAQAB";
    String format = "json";
    String charset = "UTF-8";
    String sig = "RSA2";

    @Autowired
    private IOrderService orderService;

    @RequestMapping("/alipay")
    public void alipay(HttpServletResponse response,String orderId,Integer userId) throws Exception {

        System.out.println("orderId:"+orderId);
        System.out.println("userId:"+userId);


        // 1.根据orderId查询order对象
        Order order = orderService.getOrderById(userId, orderId);

        // 1.创建支付的客户端
        AlipayClient alipayClient = new DefaultAlipayClient(
                // 支付宝网关，需要设置沙箱
                serverUrl,
                // 商家创建应用后生成的appid
                appid,
                // 商家的私钥
                prikey,
                // 参数返回格式
                format,
                // 编码
                charset,
                // 支付宝的公钥，从沙箱中可以看到
                pubKey,
                // 设置签名的算法
                sig
        );  //获得初始化的AlipayClient

        // 2.创建一个请求对象
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest(); //创建API对应的request

        // 设置同步跳转地址
        alipayRequest.setReturnUrl("http://localhost/shop-home");
        // 设置异步通知的地址 （支付通知商家扣款是否成功)
        alipayRequest.setNotifyUrl("http://b72xuf.natappfree.cc/pay/updateOrderStatus"); //在公共参数中设置回跳和通知地址

        // 3.设置要传递给支付的参数
       // long orderId = System.currentTimeMillis();

        System.out.println("orderId:" + orderId);
        alipayRequest.setBizContent("{" +
                "    \"out_trade_no\":" + orderId + "," +
                "    \"product_code\":\"FAST_INSTANT_TRADE_PAY\"," +
                "    \"total_amount\":" + order.getTotalPrice()+ "," +
                "    \"subject\":\"2002-shop\"," +
                "    \"body\":\"2002-shop\"" +
                "  }");

        String form = "";
        try {
            form = alipayClient.pageExecute(alipayRequest).getBody();  //调用SDK生成表单
//            System.out.println(form);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        response.setContentType("text/html;charset=utf8");
        response.getWriter().write(form); //直接将完整的表单html输出到页面
        response.getWriter().flush();
        response.getWriter().close();
    }

    @RequestMapping(value = "/updateOrderStatus", method = RequestMethod.POST)
//    public void updateOrderStatus(String out_trade_no, String trade_no, String trade_status, String total_amount) throws Exception {
    public void updateOrderStatus(HttpServletRequest request) throws Exception {

//        System.out.println("订单号：" + out_trade_no);
//        System.out.println("支付宝交易号：" + trade_no);
//        System.out.println("支付状态：" + trade_status);
//        System.out.println("订单金额：" + total_amount);

        // 1.定义一个map用来接收支付宝传递过来的参数
        Map<String, String> params = new HashMap<String, String>();

        // 2.循环遍历添加到params
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("paras:"+params);
        // 验证
        boolean signVerified = AlipaySignature.rsaCheckV1(params, pubKey, charset, sig); //调用SDK验证签名
        if (signVerified) {
            System.out.println("当前请求是支付宝调用。。。。。");
            // 处理业务逻辑
            String orderId = params.get("out_trade_no");
            String trade_status = params.get("trade_status");

            if("TRADE_SUCCESS".equals(trade_status)){
                // 交易成功。。。
                // 时间+后四位+流水号
//                orderService.updateOrderStatus(orderId,"2"); // 1: 2: 3: 4:
                System.out.println("修改订单的状态的为已支付");
                orderService.updateOrderStatus(orderId,"2");
            }
//            test(out_trade_no);
        }else{
            System.out.println("接口是一个非正常的请求");
        }


    }

    // 调用支付宝的查询接口，判断订单支付状态
    @RequestMapping("/test")
    public void test(String oid) throws AlipayApiException {

        AlipayClient alipayClient = new DefaultAlipayClient(
                serverUrl,
                appid,
                prikey,
                format,
                charset,
                pubKey,
                sig
        );

        // 创建一个查询的请求
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();

        request.setBizContent("{" + "\"out_trade_no\":" + oid + "}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println(response.getBody());
        if (response.isSuccess()) {
            System.out.println("调用成功");
        } else {
            System.out.println("调用失败");
        }
    }

}
